package com.klikmee.sms.core.base.communicator.mtel;

import java.text.MessageFormat;

import javax.persistence.NoResultException;

import org.apache.log4j.Logger;

import com.klikmee.sms.core.base.communicator.AbstractDeliveryReport2MessageResolver;
import com.klikmee.sms.core.base.communicator.DeliveryReport;
import com.klikmee.sms.core.base.exceptions.DeliveryReportNotResolvedException;
import com.klikmee.sms.core.commons.exceptions.ErrorInfo;
import com.klikmee.sms.core.model.OutgoingMessage;
/**
 * Delivery report resolver for MTel operator.
 */
public class MtelDeliveryReport2MessageResolverImpl extends AbstractDeliveryReport2MessageResolver{

	private Logger logger = Logger.getLogger( MtelDeliveryReport2MessageResolverImpl.class );
	/**
	 * Resolves delivery report by providers message id and provider
	 * @param deliveryReport holder for delivery report info
	 * @return sent message for this delivery report
	 * @throws DeliveryReportNotResolvedException in case when sent message could not be found
	 */
	@Override
	public OutgoingMessage resolve(DeliveryReport deliveryReport) throws DeliveryReportNotResolvedException {
		
		try {
			OutgoingMessage resolved = outgoingMessageDAO.findByProvidersMessageIdAndProvider(deliveryReport.getProvidersMessageId(), deliveryReport.getProvider());
			logger.debug( MessageFormat.format( "Resovled MTel status report to message with id = [{0}]", resolved.getId() ) );
			
			return resolved;
		} catch (NoResultException e) {
			logger.debug( MessageFormat.format( "Could not find outgoing message by providers message id = [{0}], throwing ex", deliveryReport.getProvidersMessageId() ) );
			
			DeliveryReportNotResolvedException exception = new DeliveryReportNotResolvedException("Could not resolve delivery report for MTel communicator");
			ErrorInfo errorInfo = exception.addInfo();
			errorInfo.getParameters().put("ProvidersMessageId", deliveryReport.getProvidersMessageId());
			errorInfo.setContextId( "OnDeliveryReport/MTelDeliveryReportResovler" );
			errorInfo.setErrorId( "Status report not resovled" );
			
			throw exception;
			/*logger.debug( MessageFormat.format( "Could not find outgoing message by providers message id = [{0}], probably bulk message, ignorring", deliveryReport.getProvidersMesssageId() ) );
			return null;*/
		}
	}
	@Override
	public String toString() {
		
		return "MTel D2M resover";
	}
	
	

}
